﻿using Core.Framework;
using iTool.PluginCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace Plugin.MessageProvider
{
    public class LoginMpWeiXin : ILServerPlugin
    {
        public string Name { get; }

        private IConfiguration configuration;
        public LoginMpWeiXin(IConfiguration configuration)
        {
            this.Name = "LoginProvider";
            this.configuration = configuration;
        }
        [ExportMethod("WxLogin")]
        public async Task<string> WxLogin(string code)
        {
            var result = "";
            try
            {
                var link = this.configuration.GetSection("WChat").GetSection("ApiUrl").Value;
                var appid = this.configuration.GetSection("WChat").GetSection("Appid").Value;
                var secret = this.configuration.GetSection("WChat").GetSection("Secret").Value;
                var parameter = $"appid={appid}&secret={secret}&grant_type=authorization_code&js_code={code}";
                var path = $"{link}?{parameter}";

                var client = HttpClientFactory.Create();
                client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
                var response = await client.GetAsync(path);

                if (response.IsSuccessStatusCode)
                {
                    var value = await response.Content.ReadAsStringAsync();
                    var dic = value.TryToEntity<Dictionary<string, string>>();
                    if (dic.ContainsKey("openid"))
                    {
                        result = dic["openid"];
                    }

                    return result;
                }
                else
                {
                    return string.Empty;
                }

            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
